package com.weiwei.netphone;

import java.io.RandomAccessFile;
import java.util.Properties;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import com.weiwei.base.activity.VsBaseActivity;
import com.weiwei.base.activity.login.VsLoginActivity;
import com.weiwei.base.activity.login.VsStartActivity;
import com.weiwei.base.activity.more.UnlockGesturePasswordActivity;
import com.weiwei.base.application.VsApplication;
import com.weiwei.base.common.CustomLog;
import com.weiwei.base.common.VsBizUtil;
import com.weiwei.base.common.VsNetWorkTools;
import com.weiwei.base.common.VsUtil;
import com.weiwei.base.dataprovider.DfineAction;
import com.weiwei.base.dataprovider.GlobalVariables;
import com.weiwei.base.dataprovider.VsUserConfig;
import com.weiwei.base.db.provider.VsPhoneCallHistory;
import com.weiwei.base.http.VsHttpTools;
import com.weiwei.base.service.VsCoreService;
import com.weiwei.json.me.JSONArray;
import com.weiwei.json.me.JSONException;
import com.weiwei.json.me.JSONObject;
import com.weiwei.lock.LockPatternUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import com.hwtx.jytxdh.R;

public class SplashActivity extends VsBaseActivity {
	/**
	 * This must be false for production. If true, turns on logging, test code,
	 * etc.
	 */
	private final char GOTO_VSMAIN = 1;// 跳转主页面
	private final char MSG_SPLASH = 2;// 跳转到滑屏页面
	private final char MSG_VSSTART = 3;// 跳转到登陆页面
	private ImageView splash_screen_img;
	private String ad_str;
	private String img_url;
	private String TAG = "SplashActivity";
	private ImageLoader imageLoader = ImageLoader.getInstance();

	@Override
	protected void handleBaseMessage(Message msg) {
		super.handleBaseMessage(msg);
		switch (msg.what) {
		case GOTO_VSMAIN:/*
						 * Intent intent = new Intent(mContext,
						 * VsMainActivity.class); startActivity(intent);
						 * VsBizUtil.getInstance().getRYToken(mContext, "0");
						 * VsBizUtil.getInstance().getToken(mContext); finish();
						 */
			RandomAccessFile raf;
			try {
				raf = new RandomAccessFile(
						LockPatternUtils.sLockPatternFilename, "rwd");
				if (raf.length() == 0) {
					Intent intent = new Intent(mContext, VsMainActivity.class);
					startActivity(intent);
//					VsBizUtil.getInstance().getRYToken(mContext, "0");
					VsBizUtil.getInstance().getToken(mContext);
					finish();
				} else {
					Intent intent = new Intent(this,
							UnlockGesturePasswordActivity.class);
					if (link != null && link.length() > 0) {
						intent.putExtra("messagelink", link);
					}
					startActivity(intent);
					finish();
				}

				raf.close();
				finish();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finish();

			break;
		case MSG_SPLASH:
			startActivity(this, SlideActivity.class);
			finish();
			break;
		case MSG_VSSTART:
			startActivity(this, VsMainActivity.class);
			finish();
			break;
		default:
			break;
		}
	}

	private String link;// 外部要跳转的链接

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		VsUserConfig.setData(mContext, VsUserConfig.JKey_Code_Account, "");
		// 获取屏幕宽高与密度
		VsUtil.setDensityWH(this);
		// 获取手机型号
		GlobalVariables.PHONE_MODEL = android.os.Build.MODEL;
		CustomLog.i(TAG, "手机型号:" + GlobalVariables.PHONE_MODEL);

		// 防止外部修改我们的包名
		String packageName = getApplication().getPackageName();
		if (!packageName.equals(DfineAction.PACKAGE_FIRST)
				&& !packageName.equals(DfineAction.PACKAGE_SECOND)) {
			finish();
			return;
		}
		if (VsPhoneCallHistory.IMCONTACTLIST == null
				|| VsPhoneCallHistory.IMCONTACTLIST.size() == 0) {
			// VsPhoneCallHistory.loadContacts();
			VsPhoneCallHistory.loadContactData(SplashActivity.this, 1);
		}

		// 初始化变量
		getVersionCode();
		init();
		boolean login = VsUtil.checkHasAccount(mContext);

		Intent intent = getIntent();
		link = intent.getStringExtra("messagelink");
		if (link != null && link.length() > 0) {
			VsUtil.startActivity(link, mContext, null);
			finish();
		}
		// 加载钢琴音
		VsCoreService.getData();
		if (VsUserConfig.getDataInt(mContext,
				VsUserConfig.JKEY_PIANO_ISCHECHED_ID) != 0) {
			VsCoreService.setSpData(VsUserConfig.getDataInt(mContext,
					VsUserConfig.JKEY_PIANO_ISCHECHED_ID), mContext);
		}
		// 加载通话记录
		if (!VsUserConfig.getDataBoolean(mContext,
				VsUserConfig.JKEY_FRIST_LOAD_CALLLOG, true)) {
			VsPhoneCallHistory.loadCallLog();
		}

		// 用户清空账号手动退出。下次进入软件直接进入到登录界面
		if (VsUserConfig.getDataBoolean(mContext,
				VsUserConfig.JKEY_ISLOGOUTBUTTON, false) && !login) {
			// startActivity(this, VsStartActivity.class);
			// finish();
			mBaseHandler.sendEmptyMessageDelayed(MSG_VSSTART, 1300);
			return;
		}

		// 有帐号记录，去拉取各类配置信息
		startLoadInfo(login);
		ad_str = VsUserConfig.getDataString(mContext,
				VsUserConfig.JKEY_AD_CONFIG_400501);
		if (ad_str.length() > 1) {

			try {
				JSONArray ad_conf = new JSONArray(ad_str);
				JSONObject ad_object = (JSONObject) ad_conf.get(0);
				img_url = ad_object.getString("img");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		initView();
		// 首次进入软件
		if (VsUserConfig.getDataBoolean(mContext,
				VsUserConfig.JKEY_FRIST_LOGIN_APP, true)) {
			VsUtil.CreateDeskShortCut(mContext, getString(R.string.app_name),
					R.drawable.icon);
			VsUserConfig.setData(mContext, VsUserConfig.JKEY_FRIST_LOGIN_APP,
					false);
			mBaseHandler.sendEmptyMessageDelayed(MSG_VSSTART, 2500);
			return;
		}

		if (intent != null) {
			// 手机拨号盘拨打
			Uri uri = intent.getData();
			if (uri != null) {
				if (uri.toString().startsWith(DfineAction.scheme_head)) {
					VsUtil.skipForScheme(uri.toString(), mContext, null);
					finish();
					return;
				} else {
					String tempStr = uri.toString();
					tempStr = tempStr.replaceAll("%20", "")
							.replaceAll("%2B86", "").replaceAll("%2B", "");
					// 去掉tel:
					tempStr = tempStr.substring(4);
					if (tempStr.indexOf("%") == -1) {
						// 拨打
						VsUtil.callNumber(tempStr, tempStr, "", mContext, "",
								true);
						finish();
						return;
					}
				}
			}
		}

		if (!VsUtil.checkHasAccount(mContext)) {
			// startActivity(this, VsStartActivity.class);
			// finish();
			unRgisterGO();
//			mBaseHandler.sendEmptyMessageDelayed(MSG_VSSTART, 1300);
		} else {
			unRgisterGO();
		}

		if (!VsUserConfig.getDataBoolean(mContext,
				VsUserConfig.JKEY_TJ_ONE_START, false)) {
			VsUserConfig
					.setData(mContext, VsUserConfig.JKEY_TJ_ONE_START, true);
		}

		VsApplication.getInstance().addActivity(this);
	}

	private void initView() {
		// setContentView(R.layout.splashregister);
		// final LinearLayout centerLL = (LinearLayout)
		// findViewById(R.id.center_ll);
		// ImageView splash_img = (ImageView) findViewById(R.id.splash_image);
		// String url = VsUserConfig.getDataString(mContext,
		// VsUserConfig.JKEY_AD_CONFIG_400501);
		// if (url.length() > 1) {
		// imageLoader.displayImage(url, splash_img);
		// } else {
		// splash_img.setImageResource(R.drawable.vs_splash_img);
		// }

		setContentView(R.layout.splashregister);
		splash_screen_img = (ImageView) findViewById(R.id.splash_image);
		if (img_url != null && img_url.length() > 1) {
			imageLoader.displayImage(img_url, splash_screen_img);
		} else {
			splash_screen_img.setImageResource(R.drawable.vs_splash_img);
		}
		splash_screen_img.setScaleType(ScaleType.FIT_XY);

		// final AdDataView adDataView = (AdDataView)
		// findViewById(R.id.ad_data_view);
		/*
		 * if (AdManager.getInstance().hasAd(SplashActivity.this,
		 * AdManager.TYPE_START_PAGE)) { TranslateAnimation animation = new
		 * TranslateAnimation(0, 0, 0, (int) (GlobalVariables.height * 0.389));
		 * animation.setDuration(300L); animation.setFillAfter(true);
		 * centerLL.startAnimation(animation);
		 * animation.setAnimationListener(new Animation.AnimationListener() {
		 * 
		 * @Override public void onAnimationStart(Animation animation) {
		 * companyTV.setVisibility(View.GONE); }
		 * 
		 * @Override public void onAnimationEnd(Animation animation) {
		 * adDataView.setLayoutParams(new RelativeLayout.LayoutParams(-1, (int)
		 * (GlobalVariables.height * 0.778)));
		 * adDataView.setAdData(AdManager.getInstance
		 * ().getAd(SplashActivity.this, AdManager.TYPE_START_PAGE, new
		 * Random().nextInt(5)), false); }
		 * 
		 * @Override public void onAnimationRepeat(Animation animation) {
		 * 
		 * } }); } else { adDataView.setVisibility(View.GONE); }
		 */

	}

	@Override
	protected void onResume() {
		super.onResume();
		setDisEnableLeftSliding();
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		
	}

	/**
	 * 初始化变量信息
	 */
	public void init() {
		GlobalVariables.netmode = VsNetWorkTools.getSelfNetworkType(mContext);
		if (VsHttpTools.getInstance(mContext).getUri_prefix().trim().length() < 1
				|| VsUserConfig.getDataString(mContext,
						VsUserConfig.JKey_UriAndPort) == null) {
			VsUserConfig.setData(mContext, VsUserConfig.JKey_UriAndPort,
					DfineAction.RES.getString(R.string.uri_prefix));
			VsHttpTools.getInstance(mContext).setUri_prefix(
					VsUserConfig.getDataString(mContext,
							VsUserConfig.JKey_UriAndPort));
		}
		// VsBizUtil.getInstance().defaultConfig(mContext);// 多点接入
		try {
			// 初始化渠道号和版本号
			Properties properties = new Properties();
			properties.load(getAssets().open("config.properties"));
			DfineAction.invite = properties.getProperty("inviete", "5");
			DfineAction.v = VsUtil.getAppVersionName(mContext);
			VsUserConfig.setData(mContext, VsUserConfig.JKEY_INVITEDBY,
					DfineAction.invite);

			// 第一次进入或者升级安装
			if (!DfineAction.v.equals(VsUserConfig.getDataString(mContext,
					VsUserConfig.JKey_V, ""))) {// 版本号不同
				// 保存版本号信息
				VsUserConfig.setData(mContext, VsUserConfig.JKey_V,
						DfineAction.v);
				// 上报安装
				VsUserConfig.setData(mContext,
						VsUserConfig.JKey_RECORDINSTALL_NO_UID, true);
				VsUserConfig.setData(mContext,
						VsUserConfig.JKey_RECORDINSTALL_WITH_UID, true);
				// 滑屏。升级安装需要显示滑屏
				VsUserConfig.setData(mContext,
						VsUserConfig.JKEY_FRIST_LOGIN_APP, true);
			}

			String isTestV = properties.getProperty("istestv", "no");
			CustomLog.setPrintlog(isTestV.equals("yes"));// 设置是否显示Log信息
			properties.clear();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 启动拉取
	 */
	public void startLoadInfo(boolean login) {

		// 判断网络
		if (GlobalVariables.netmode == 0) {
			return;
		}

		// app静态配置
			VsBizUtil.getInstance().getAppInfo(mContext);
			//升级信息
            VsUtil.getUpdate(mContext);
			// fir升级
			VsBizUtil.getInstance().getFirUpDate(mContext);
		// 有帐号拉取
		if (login) {
			// 模版配置
			VsBizUtil.getInstance().templateConfig(mContext);
			//分享内容拉取
			VsBizUtil.getInstance().getShareContent(mContext);
			// 广告信息
			
			VsBizUtil.getInstance().getAdInfos(mContext,VsUserConfig.getDataString(mContext, VsUserConfig.JKey_KcId));
			
			//拉取个人信息
			VsBizUtil.getInstance().getMyInfoText(mContext);
		} else {
			if (!VsUserConfig.getDataBoolean(mContext,
					VsUserConfig.JKEY_ISLOGOUTBUTTON, false)) {
				// 读取本地保存的帐号密码并登录
				VsBizUtil.getInstance().redSDCardInfo(mContext);
			}
		}
	}

	public void unRgisterGO() {
		showVS2011(1300);
	}

	public void onDestroy() {
		super.onDestroy();
	}

	public void showVS2011(int tm) {
		mBaseHandler.sendEmptyMessageDelayed(GOTO_VSMAIN, tm);
	}
	
	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public String getVersionCode() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = Integer.toString(info.versionCode);
			 VsUserConfig.setData(mContext, VsUserConfig.JKey_FIRVERSION, version);
			return "V" + version;
		} catch (Exception e) {
			e.printStackTrace();
			return this.getString(R.string.version_unkown);
		}
	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();
	}
}
